package com.david.viewtest.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.View
import android.view.ViewConfiguration
import android.widget.Scroller


class InertialScrollView : View {
    private var mScroller: Scroller? = null
    private var mVelocityTracker: VelocityTracker? = null
    private var mLastY = 0

    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
        init(context)
    }

    private fun init(context: Context) {
        mScroller = Scroller(context)
        mVelocityTracker = VelocityTracker.obtain()

        post {
            scrollBy(50, 50)
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        mVelocityTracker!!.addMovement(event)
        val y = event.y.toInt()
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                if (!mScroller!!.isFinished) {
                    mScroller!!.abortAnimation()
                }
                mLastY = y
            }

            MotionEvent.ACTION_MOVE -> {
                val dy = y - mLastY
                mScroller!!.startScroll(0, mScroller!!.finalY, 0, -dy)
                invalidate()
                mLastY = y
            }

            MotionEvent.ACTION_UP -> {
                mVelocityTracker!!.computeCurrentVelocity(1000)
                val initialVelocity = mVelocityTracker!!.yVelocity.toInt()
                if (Math.abs(initialVelocity) > ViewConfiguration.get(context).scaledMinimumFlingVelocity) {
                    mScroller!!.fling(0, mScroller!!.finalY, 0, -initialVelocity, 0, 0, Int.MIN_VALUE, Int.MAX_VALUE)
                }
            }
        }
        return true
    }

    override fun computeScroll() {
        if (mScroller!!.computeScrollOffset()) {
            scrollTo(0, mScroller!!.currY)
            postInvalidate()
        }
    }
}
